package com.sline.servlet.demo2_cookie_session;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

@WebServlet("/session/login")
public class login extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html; charset=UTF-8");

        String username = req.getParameter("username");
        String password = req.getParameter("password");

        HttpSession session = req.getSession();
        String sessionId = session.getId();
        session.setAttribute("username", username);
        // 设置session的有效时间
        //session.setMaxInactiveInterval(5);
        // 立刻删除一个session
        //session.invalidate();
        System.out.println("sessionId: " + sessionId);

        String url = resp.encodeURL("/servlet/session/inbox");

        PrintWriter writer = resp.getWriter();
        writer.println("尊敬的: " + username);
        writer.println("<a href='" + url + "'>收件箱</a>");
    }
}
